import yaml
import os
import time
from joblib import dump as joblib_dump
from joblib import load as joblib_load
import numpy as np
import cv2
from skimage import feature
# 获取 0_setting.yaml 中的键 key 对应的值 value
def get(key):
    with open('0_setting.yaml', 'r' ,encoding='utf-8') as file:
        data = yaml.safe_load(file)
    value = data[key]
    return value

# 预处理图像, 把图像设置为指定大小之后，展平返回
def preprocess_image(file_name, new_size):
    # 1. 读取图像灰度图
    img = cv2.imdecode(np.fromfile(file_name), cv2.IMREAD_GRAYSCALE)

    # 2. 调整图像大小为 new_size
    img = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)

    # 3.使用HOG特征提取
    hog = feature.hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2))

    return hog

# 用joblib把叫做 name 的对象 obj 保存(序列化)到位置 loc
def dump(obj, name, loc):
    start = time.time()
    print(f"把{name}保存到{loc}")
    joblib_dump(obj, loc)  # 此处序列化对象
    end = time.time()
    print(f"保存完毕,文件位置:{loc}, 大小:{os.path.getsize(loc) / 1024 / 1024:.3f}M")
    print(f"运行时间:{end - start:.3f}秒")

# 用joblib读取(反序列化)位置loc的对象obj,对象名为name
def load(name, loc):
    print(f"从{loc}提取文件{name}")
    obj = joblib_load(loc)  # 此处反序列化对象
    return obj